package com.sws.worktive.jobs_service;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;

import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.sws.worktive.R;
import com.sws.worktive.jobs_service.JobsJsonParser.JobData;
import com.sws.worktive.volley.MyVolley;

public class JobFetcher {
	public static final String JOBS_URL = "http://www.worktive.com/api/index.php/jobs/33.924485/-84.013097/5/0/7dea6e8128c3c4120aa1016ded6aee9e";
	
	private Context mContext;
	
	private ProgressDialog progressDialog;	
	
	public static interface JobReceiverListener{
		void jobListReceived(JobData[] jobDatas);
	}
	
	public JobFetcher(Context context){
		mContext = context;
	}
	
	public void fetchJobs(JobReceiverListener jobReceiverListener){
		progressDialog = ProgressDialog
				.show(mContext, "", mContext.getResources()
						.getString(R.string.loading_jobs));
		
		JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
				Method.GET, 
				JOBS_URL, 
				null, 
				createSuccessListener(jobReceiverListener), 
				createErrorListener());
		MyVolley.getMyVolley(mContext).addToRequestQueue(jsonObjectRequest);
	}
	
	private Response.Listener<JSONObject> createSuccessListener(final JobReceiverListener jobReceiverListener){
		return new Response.Listener<JSONObject>() {
			@Override
			public void onResponse(JSONObject jsonObject) {
				try {
					int status = jsonObject.getInt("status");
					JobData[] jobsDatas = new JobsJsonParser().parseJobsJsonObject(jsonObject);
					jobReceiverListener.jobListReceived(jobsDatas);
					if (progressDialog.isShowing()) {
						progressDialog.dismiss();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				
			}
		};
	}
	
	private Response.ErrorListener createErrorListener() {
		return new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError arg0) {
			}
		};
	}
	
	
}
